<template>
    <view :class="uiStyle == 1 ? '' : 'uiStyle'">
        <!-- 预约临停 -->
		<view class="head-block" v-if="weixin == 2">
				     <view class="nav-title" :style="'top:10px'"></view>
					 <!-- 返回 -->
					 <view class="icon" @tap="goMy" :style="'top:6px'">
					      <van-icon name="arrow-left" color="#333" size="45rpx" />
					  </view>
				 </view>
        <topBar text="预约" :needBack="true"></topBar>
        <view style="position: relative;">
            <view class="select">已选择<text class="surplus" v-if="realFreeNum">剩余车位：{{realFreeNum}}</text></view>
            <view class="card-top">
                <image src="../../static/assets/img/greencard.png" class="bg-img"></image>
                <view class="card-top-contain">
                    <view class="bg-selected">{{ spaceNo ? '固定车位' : '不固定车位' }}</view>
                    <view class="park-title" v-if="!spaceNo">
                        <image src="../../static/assets/img/pos.png" class="tagimg" mode="widthFix" style="width: 24rpx"></image>
                        {{ datas.parkingName || '暂未获取到车场名称' }}
                    </view>
                    <view class="park-title" v-else>
                        <text v-if="spaceNo">车 位 号：{{ spaceNo }}</text>
                    </view>
                    <view class="flex-content" v-if="!spaceNo">
                        <!-- <image src="../../assets/img/addressicon.png" class="tagimg"></image> -->
                        <view class="pop-address1">{{ datas.address || '暂无地址' }}</view>
                    </view>
                    <view class="park-title2" v-else>
                        共享日期：{{ manage.validStartTime1 }}-{{ manage.validEndTime1 }}
                        <text v-if="manage.tempCycle2[0] == '1'">周一</text>
                        <text v-if="manage.tempCycle2[1] == '1'">周二</text>
                        <text v-if="manage.tempCycle2[2] == '1'">周三</text>
                        <text v-if="manage.tempCycle2[3] == '1'">周四</text>
                        <text v-if="manage.tempCycle2[4] == '1'">周五</text>
                        <text v-if="manage.tempCycle2[5] == '1'">周六</text>
                        <text v-if="manage.tempCycle2[6] == '1'">周日</text>
                    </view>
                    <view class="park-title2" v-if="spaceNo">
                        价 格：{{ manage.unitPrice / 100 }}元/次
                        <text v-if="haveCharge">（本车位可提供充电服务，费用双方自行商议）</text>
                        <!-- <text>（国标/特斯拉专用）</text> -->
                    </view>
                    <view class="park-title2">开放时间段：<text>{{ datas.openTime }}</text> </view>
                    <view
                        :class="'parkrecommend ' + (focus == 1 ? 'like1' : 'nolike1') + ' '"
                        :data-item="datas"
                        :data-index="index"
                        :data-isFocus="focus"
                        :data-id="spaceNo ? spaceNoId : datas.parkingCode"
                        @tap.stop.prevent="likeThisPark"
                    >
                        {{ focus == 1 ? '已关注' : '+关注' }}
                    </view>
                    <view class="price-rt" v-if="!spaceNo">
						<view class="price-strong" v-if="price.unitPrice / 100==0">免费</view>
						<view v-else>
							<view class="price-strong" >{{ price.unitPrice / 100 || '--' }}</view>
							元/小时
						</view>
                        
                    </view>

                    <view v-else>
                        <van-rate readonly v-model="evaluate" color="#ffd21e" void-icon="star" void-color="#eee" />
                    </view>
					<view class="flex_b">
						<view class="statu" style="display: flex; padding: 0 30rpx; min-height: 30rpx">
						    <view class="statuView" v-if="manage.haveCharge ? manage.haveCharge : datas.haveCharge">
						        <image class="img-tag" mode="widthFix" src="../../static/assets/img/elc.png" />
						        有充电桩
						    </view>
						    <view class="statuView" v-if="manage.buildType ? manage.buildType : datas.buildType == 2">
						        <image class="img-tag" mode="widthFix" src="../../static/assets/img/under.png" />
						        地下
						    </view>
						    <view class="statuView" v-if="manage.buildType ? manage.buildType : datas.buildType == 1">
						        <image class="img-tag" mode="widthFix" src="../../static/assets/img/ground.png" />
						        地面
						    </view>
						    <view class="statuView" v-if="manage.buildType ? manage.buildType : datas.buildType == 3">
						        <image class="img-tag" mode="widthFix" src="../../static/assets/img/3dpark.png" />
						        立体车库
						    </view>
						</view>
						<view class="" :data-id="datas.contactPhone" @tap="handlePhoneWy">
						    <image src="../../static/assets/img/telphone.png" class="tagimg"></image>
						    <!-- {{ datas.contactPhone || '暂无联系方式' }} -->
							<text class="car_phone">联系车场</text>
						</view>
					</view>
					
                </view>
            </view>
            <view class="split-line"></view>
            <!-- 选择日期start -->
            <view class="card-middle">
                <!-- <view class="park-title">请选择：</view> -->
                <view class="cell-btm">
                    <van-cell title="您的到达时间" is-link @click="showParkFun">
                        <span :class="parkTimeStart != '请选择' ? 'infoText' : ''">{{ parkTimeStart }}</span>
                    </van-cell>
                    <van-cell title="预计离场时间" is-link @click="showPark2Fun">
                        <span :class="parkTimeEnd != '请选择' ? 'infoText' : ''">{{ parkTimeEnd }}</span>
                    </van-cell>
                    <van-cell title="您的车牌号" is-link @click="showCarFun">
                        <span :class="carNo != '请选择' ? 'infoText' : ''">{{ carNo }}</span>
                    </van-cell>
                </view>
            </view>
            <!-- 选择日期end -->
            <!-- <view class="tips-box"  wx:if="{{datas.payType == 1}}">
    <view class="tip-title"><image src="/assets/img/usetip.png"></image>温馨提醒：</view>
    <view class="tip-content">1、准时或提前到达，根据车辆实际进场/离场时间段计费。</view>
    <view class="tip-content">2、晚于预约时间到达，还需额外支付预约时间到实际入场时间的车位占用费用。</view>
    <view class="tip-content">3、若超过预约时间再取消，则需要支付预约时间到取消时间的车位占用费用。</view>
    <view class="tip-content">4、请在车位共享时段内使用，超时停车将按临停单价*3倍计算费用。</view>
  </view>
  <view class="tips-box"  wx:else>
    <view class="tip-title"><image src="/assets/img/usetip.png"></image>温馨提醒：</view>
    <view class="tip-content">1、该车场预约即为您预留车位。</view>
    <view class="tip-content">2、根据车辆实际进场/离场时间现场缴费，线上无需支付任何费用。</view>
    <view class="tip-content">3、可提前一天免费取消预约，预约当日的订单不可取消。取消成功后，退款将在7个工作日内原路返回。</view>
  </view> -->
            <view class="tips-box" v-if="datas.parkingAttribute!=4">
                <view class="tip-title">
                    <image src="../../static/assets/img/usetip.png"></image>
                    温馨提醒：
                </view>
                <view class="tip-content">1、该车场预约即为您预留车位。</view>
                <view class="tip-content">2、根据车辆实际进场/离场时间现场缴费，线上无需支付任何费用。</view>
            </view>
			<view class="tips-box" v-if="datas.parkingAttribute==4">
				<view class="tip-title" >使用须知：</view>
				<view class="tip-content">1、车牌号需认证后方可办理。<text style="color:#00bcab" @tap="golicenseManage()">去认证 ></text></view>
				<view class="tip-content">2、离场时根据实际停车时长现场缴费。</view>
				<view class="tip-content">3、请在车位共享开放时段内停车，超时离场需根据时长缴纳超时占用费，超时达到3次后将列入黑名单影响后续正常使用。</view>
			</view>
            <view class="btn" @tap="submit">智能预约车位</view>
            <view class="rule">
                <van-checkbox v-model="checked"  checked-color="#00BCAB"></van-checkbox>
                <text @tap="showRule" class="rule-konw">
                    我已经阅读并同意
                    <text style="color: #00bcab">《停车服务协议》</text>
                </text>
            </view>
        </view>
        <view>
            <van-popup round v-model="showRulePop" @close="closeRule">
                <view class="rules">
                    <view class="rule-title">停车服务协议</view>
                    <!-- <view class="rule-content">{{platformRules}}</view> -->
                    <view class="rule-content">
                        <rich-text :nodes="platformRules"></rich-text>
                    </view>
                    <view class="rule-line"></view>
                    <view class="rule-know" @tap="closeRule">我知道了</view>
                </view>
            </van-popup>
        </view>
        <!-- 车辆下拉 -->
        <van-popup v-model="showCar" position="bottom" @close="onCloseCar">
            <van-picker show-toolbar :columns="carList" @confirm="onSelectCar" @cancel="onCloseCar" />
        </van-popup>
        <!-- 时间下拉 -->
        <van-popup v-model="showPark" position="bottom" @close="oncloseParkTime">
            <van-datetime-picker
                type="datetime"
                title="选择到达时间"
                v-model="currentDate"
                :min-date="minDate"
                :max-date="maxDate"
                @confirm="SelectDate"
                @cancel="oncloseParkTime"
                :formatter="formatter"
            />
        </van-popup>
        <!-- 时间下拉 -->
        <van-popup v-model="showPark2" position="bottom" @close="oncloseParkTime2">
            <van-datetime-picker
                type="datetime"
                title="选择离场时间"
                v-model="currentDate2"
                :min-date="minDate2"
                :max-date="maxDate2"
                @confirm="SelectDate2"
                @cancel="oncloseParkTime2"
                :formatter="formatter"
            />
        </van-popup>
        <van-dialog id="van-dialog" />
        <van-toast id="van-toast" />
        <van-dialog
            id="van-dialog2"
            v-model="isShowPayTip"
            title="支付提醒"
            confirm-button-text="去支付"
            cancel-button-text="稍后再看"
            confirm-button-color="#00BCAB"
            cancel-button-color="#AEAEAE"
            v-model-cancel-button="true"
            message="您有订单未支付，请尽快支付"
            @confirm="gotoPay($event, { tagId: 'van-dialog2' })"
        />
    </view>
</template>

<script>
// import vanCell from '@vant/weapp/cell/index';
// import vanCellGroup from '@vant/weapp/cell-group/index';
// import vanCheckbox from '@vant/weapp/checkbox/index';
// import vanDatetimePicker from '@vant/weapp/datetime-picker/index';
// import vanPicker from '@vant/weapp/picker/index';
import config from './../../utils/config.js';
import util from './../../utils/util.js';
import api from './../../utils/api.js';
// import Dialog from '@vant/weapp/dialog/dialog';
import { Toast } from 'vant';
// import Toast from '@vant/weapp/toast/toast';
export default {
    components: {
        // vanCell,
        // vanCellGroup,
        // vanCheckbox,
        // vanDatetimePicker,
        // vanPicker
    },
    data() {
        return {
            focus: 0,
            carNo: '请选择',
            parkTimeStart: '请选择',
            parkTimeEnd: '请选择',
            showCar: false,
            showPark: false,
            showPark2: false,
            checked: false,
            showRulePop: false,

            datas: {
                address: '',
                haveCharge: '',
                buildType: 0,
                parkingCode: '',
                contactPhone: ''
            },

            rules1: '',
            carList: '',
            minDate: new Date(),
            maxDate: new Date(new Date().getTime() + 24 * 60 * 60 * 1000),
            minDate2: new Date(),
            maxDate2: new Date(new Date().getTime() + 24 * 60 * 60 * 1000),
            st1: '',
            st2: '',
            ed1: '',
            ed2: '',
            currentDate: new Date().getTime() + 60 * 15 * 1000,

            //当前时间+15分钟
            currentDate2: new Date().getTime(),

            filter(type, options) {
                if (type === 'minute') {
                    return options.filter((option) => option % 15 === 0);
                }

                return options;
            },

            platformRules: config.platformRules,

            formatter(type, value) {
                if (type === 'year') {
                    return `${value}年`;
                }

                if (type === 'month') {
                    return `${value}月`;
                }

                if (type === 'day') {
                    return `${value}日`;
                }

                if (type === 'hour') {
                    return `${value}时`;
                }

                if (type === 'minute') {
                    return `${value}分`;
                }

                return value;
            },

            isShowPayTip: false,
            gotopayType: '',

            price: {
                freeTime: '',
                dayFeeCap: 0,
                unitPrice: 0
            },

            //车位号
            spaceNo: '',

            spaceNoId: '',
            type: '',
            evaluate: '',
			weixin:uni.getStorageSync('weixin'),
            manage: {
                validStartTime2: '',
                validEndTime2: '',
                haveCharge: false,
                buildType: false
            },

            haveCharge: '',
			uiStyle:1,
			realFreeNum:''
        };
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
		this.uiStyle = uni.getStorageSync('uiStyle') || 1
		
		if(options.realFreeNum){
			this.setData({
				realFreeNum:options.realFreeNum
			})
		}
        if (options.focus) {
            this.setData({
                focus: options.focus
            });
        }

        if (options.spaceNoId) {
            this.setData({
                spaceNoId: options.spaceNoId
            });
        }

        if (options.spaceNo) {
            this.setData({
                spaceNo: options.spaceNo
            });
        }

        if (options.type) {
            this.setData({
                type: options.type
            });
        }

        let param = {
            parkingCode: options.param,
            type: 1,
            spaceNo: this.spaceNo ? this.spaceNo : ''
        };
        util.request(api.findProductList, param, 'GET').then((res) => {
            if (res.success) {
                let list = res.data.productList;

                if (list) {
                    list.map((item) => {
                        if (item.type == 3) {
                            this.setData({
                                price: item
                            });
                        }
                    });
                }

                if (res.data && res.data.manage) {
                    res.data.manage.validStartTime1 = res.data.manage.validStartTime.split(' ')[0];
                    res.data.manage.validEndTime1 = res.data.manage.validEndTime.split(' ')[0];
                    res.data.manage.validStartTime2 = res.data.manage.validStartTime.split(' ')[1];
                    res.data.manage.validEndTime2 = res.data.manage.validEndTime.split(' ')[1];
                    res.data.manage.tempCycle2 = res.data.manage.tempCycle.split('');
                }
				console.log(res.data)
                this.setData({
                    datas: res.data.parkingInfo,
                    evaluate: res.data.evaluate,
                    manage: res.data.manage ? res.data.manage : {}
                });
                console.log('manage:' + JSON.stringify(this.manage));
            }
        });
        this.setData({
            // rules1:param.rules1,
            carList: uni.getStorageSync('plateNos').split(','),
            carNo: uni.getStorageSync('plateNos').split(',')[0] || '请选择'
        });
        var date = new Date(); //1. js获取当前时间

        var min = date.getMinutes(); //2. 获取当前分钟

        date.setMinutes(min + 1);
        this.setData({
            // minDate: new Date().getTime() + 60 * 1 * 1000,
            // maxDate: new Date(new Date().toLocaleDateString()).getTime() + 2 * 24 * 60 * 60 * 1000 - 1,
            //new Date().getTime() + 60 * 60 * 24 * 1000
            currentDate: new Date().getTime() + 60 * 2 * 1000
        });
        this.setData({
            currentDate2: this.currentDate + 60 * 1000,
            // minDate2: this.currentDate + 60 * 1000,
            // maxDate2: new Date(new Date().toLocaleDateString()).getTime() + 2 * 24 * 60 * 60 * 1000 - 1 //this.data.currentDate + 60 * 60 * 24 * 1000
        });
        this.setData({
            parkTimeStart: util.getDate(this.currentDate, 'yyyy-MM-dd hh:mm') // parkTimeEnd:util.getDate(this.data.currentDate2,'yyyy-MM-dd hh:mm')
        }); // 从车位列表页进来的---访客身份下--暂时废弃
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {},
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        uni.removeStorageSync('searchHistory');
    },
    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {},
    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {},
    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {},
    /**
     * 页面上拉触底事件的处理函数
     */
    // onShareAppMessage: function () {
    // }
    onReachBottom: function () {},
    /**
     * 用户点击右上角分享
     */ methods: {
        handlePhoneWy(e) {
			if(uni.getStorageSync('weixin') == 3 || uni.getStorageSync('weixin') == 4){
				ZWJSBridge.phoneCall({
				  "corpId": e.currentTarget.dataset.id.toString()
				}).then(res => {
				  console.log(res)
				}).catch(err => {
				  console.log(err) 
				})
			}else{
				uni.makePhoneCall({
					phoneNumber: e.currentTarget.dataset.id.toString()
				}).catch((e) => {
					console.log(e);
				});
			}
        },
		goMy() {
		     uni.navigateBack({
		         delta: 1
		     });
		 },
        likeThisPark(event) {
            //关注车场
            let that = this;
            console.log('即将关注或取消id为：' + event.currentTarget.dataset.id);

            if (event.currentTarget.dataset.id) {
                if (that.spaceNo) {
                    //关注车位
                    let type = event.currentTarget.dataset.isfocus == 1 ? 2 : 1; //1关注，2取消关注

                    util.request(api.manageAddOrUpdateFocus + '?unionId=' + uni.getStorageSync('unionId') + '&manageId=' + event.currentTarget.dataset.id + '&type=' + type, 'get')
                        .then((res) => {
                            if (res.success) {
                                if (event.currentTarget.dataset.isfocus == 1) {
                                    //取消关注成功
                                    this.setData({
                                        focus: 0
                                    });
                                    uni.showToast({
                                        title: '取消关注成功'
                                    });
                                } else if (event.currentTarget.dataset.isfocus == 0) {
                                    //添加关注成功
                                    this.setData({
                                        focus: 1
                                    });
                                    uni.showToast({
                                        title: '关注成功'
                                    });
                                    uni.requestSubscribeMessage({
                                        tmplIds: ['G-qqlo3c5ARPqg9lPCnCrSUxAEgZ8bPfrEpd0UVE-8o'],

                                        success(sus) {},

                                        fail(err) {}
                                    });
                                }

                                if (this.active == 0) {
                                    this.getTempList();
                                } else if (this.active == 1) {
                                    this.getMonthList();
                                }
                            } else {
                                uni.showToast({
                                    title: res.msg,
                                    icon: 'none'
                                });
                            }
                        })
                        .catch((err) => {
                            console.log(err);
                        });
                } else {
                    //关注车场
                    let type = this.focus == 1 ? 2 : 1; //1关注，2取消关注

                    util.request(api.addOrUpdateFocus + '?unionId=' + uni.getStorageSync('unionId') + '&parkingCode=' + this.datas.parkingCode + '&type=' + type, 'get')
                        .then((res) => {
                            if (res.success) {
                                if (event.currentTarget.dataset.isfocus == 1) {
                                    //取消关注成功
                                    this.setData({
                                        focus: 0
                                    });
                                    uni.showToast({
                                        title: '取消关注成功'
                                    });
                                } else if (event.currentTarget.dataset.isfocus == 0) {
                                    //添加关注成功
                                    this.setData({
                                        focus: 1
                                    });
                                    uni.showToast({
                                        title: '关注成功'
                                    });
                                    uni.requestSubscribeMessage({
                                        tmplIds: ['G-qqlo3c5ARPqg9lPCnCrSUxAEgZ8bPfrEpd0UVE-8o'],

                                        success(sus) {},

                                        fail(err) {}
                                    });
                                }
                            } else {
                                uni.showToast({
                                    title: res.msg,
                                    icon: 'none'
                                });
                            }
                        })
                        .catch((err) => {
                            console.log(err);
                        });
                }
            }
        },

        onChange(event) {
            this.setData({
                checked: event.detail
            });
        },

        submit() {
            if (this.carNo == '请选择') {
				uni.showToast({
				    title: '请选择车辆',
				    icon: 'none'
				});
                return;
            }

            if (this.parkTimeStart == '请选择') {
				uni.showToast({
				    title: '请选择到达时间',
				    icon: 'none'
				});
                return;
            }

            if (this.parkTimeEnd == '请选择') {
				uni.showToast({
				    title: '请选择离场时间',
				    icon: 'none'
				});
                return;
            }

            if (this.checked == false) {
				uni.showToast({
				    title: '请勾选同意《停车服务协议》',
				    icon: 'none'
				});
                return;
            }

            let param = {
                unionId: uni.getStorageSync('unionId'),
                startTime: this.parkTimeStart,
                endTime: this.parkTimeEnd,
                parkingCode: this.datas.parkingCode,
                plateNo: this.carNo,
                rentedType: '1'
            };

            if (uni.getStorageSync('visitor_code')) {
                param.visitInviteCode = uni.getStorageSync('visitor_code');
            }

            if (this.spaceNo != '') {
                param.spaceNo = this.spaceNo;
            }

            uni.showLoading({
                title: '加载中'
            });
            let that = this;
            util.request(api.unionPayTmpParkingBook, param, 'POST')
                .then((res) => {
                    uni.hideLoading();
					console.log(res)
                    if (res.success) {
						uni.showToast({
						    title: '预约成功',
						    icon: 'success'
						});
						
						if (that.datas.payType == 2) {
						    uni.navigateTo({
						        url: '../rentSuccess/rentSuccess?from=01'
						    });
						} else {
						    uni.navigateTo({
						        url: '../rentSuccess/rentSuccess?from=01'
						    });
						}
                        uni.removeStorageSync('visitor_code');
                        uni.removeStorageSync('visitor_parkcode');
                    } else if (res.busiCode == 'waitingToPay1') {
                        this.setData({
                            gotopayType: 1,
                            isShowPayTip: true
                        });
                    } else if (res.busiCode == 'waitingToPay2') {
                        this.setData({
                            gotopayType: 2,
                            isShowPayTip: true
                        });
                    } else {
                       uni.showToast({
                       	title:res.msg,
						icon:'none'
                       })
                    }
                })
                .catch((err) => {
                    Toast(err || '接口出错了，请重试');
                });
        },

        /**
         * 选择停车时间
         */
        SelectDate(e) {
            console.log(e);
            this.setData({
                showPark: false,
                parkTimeStart: util.getDate(e, 'yyyy-MM-dd hh:mm'),
                // parkTimeEnd:util.getDate(e.detail+60*1000,'yyyy-MM-dd hh:mm'),
                // minDate2: e + 60 * 1000,
                // maxDate2: e + 60 * 60 * 24 * 1000
            });
        },

        SelectDate2(e) {
            this.setData({
                showPark2: false,
                parkTimeEnd: util.getDate(e, 'yyyy-MM-dd hh:mm')
            });
        },

        /**
         * 选择停车车辆
         */
        onSelectCar(e) {
            console.log(e);
            this.setData({
                carNo: e,
                showCar: false
            });
        },

        showCarFun() {
            this.setData({
                showCar: true
            });
        },

        showParkFun() {
            this.setData({
                showPark: true
            });
        },

        showPark2Fun() {
            this.setData({
                showPark2: true
            });
        },

        showRule() {
            this.setData({
                showRulePop: true
            });
        },

        closeRule() {
            this.setData({
                showRulePop: false,
                checked: true
            });
        },

        onCloseCar() {
            this.setData({
                showCar: false
            });
        },

        oncloseParkTime() {
            this.setData({
                showPark: false
            });
        },

        oncloseParkTime2() {
            this.setData({
                showPark2: false
            });
        },

        /**跳转支付 */
        gotoPay(e, _dataset) {
            /* ---处理dataset begin--- */
            this.datasetHandle(e, _dataset);
            /* ---处理dataset end--- */
            uni.navigateTo({
                url: '../order/index?type=' + this.gotopayType
            });
        },
		golicenseManage(){
			uni.navigateTo({
				url:'../licenseManage/licenseManage'
			})
		}
    }
};
</script>
<style>
@import './newBookpark.css';
</style>
